package com.newtouch.bxzs.business.train.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.business.train.mapper.ExaminationQuestionMapper;
import com.newtouch.bxzs.business.train.mapper.ExaminationQuestionsOptionMapper;
import com.newtouch.bxzs.business.train.model.bo.ExaminationPaperSetExaminationQuestionListBO;
import com.newtouch.bxzs.business.train.model.bo.ExaminationQuestionListBO;
import com.newtouch.bxzs.business.train.model.bo.ExaminationQuestionOptionListBO;
import com.newtouch.bxzs.business.train.model.bo.QuestionBankSetExaminationQuestionListBO;
import com.newtouch.bxzs.business.train.model.vo.ExaminationPaperSetExaminationQuestionListVO;
import com.newtouch.bxzs.business.train.model.vo.ExaminationQuestionListVO;
import com.newtouch.bxzs.business.train.model.vo.ExaminationQuestionOptionListVO;
import com.newtouch.bxzs.business.train.model.vo.ModifyExaminationQuestionInfoVO;
import com.newtouch.bxzs.business.train.model.vo.ModifyExaminationQuestionOptionVO;
import com.newtouch.bxzs.business.train.model.vo.QuestionBankSetExaminationQuestionListVO;
import com.newtouch.bxzs.business.train.service.ExaminationQuestionService;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.ExaminationQuestion;
import com.newtouch.bxzs.common.base.model.ExaminationQuestionsOption;
import com.newtouch.bxzs.common.base.model.bo.PageParam;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import io.netty.util.internal.StringUtil;

/**
 * 试题业务处理
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021年2月7日</td>
 * <td>dongjinlin</td>
 * <td>Create</td>
 * </tr>
 * </table>
 * 
 * @author dongjinlin
 * 
 * @version
 * @since
 */
@Service
public class ExaminationQuestionServiceImpl implements ExaminationQuestionService {

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(ExaminationQuestionService.class);

    @Autowired
    private ExaminationQuestionMapper examinationQuestionMapper;

    @Autowired
    private ExaminationQuestionsOptionMapper examinationQuestionsOptionMapper;

    /**
     * 查询题库设置试题列表
     *
     * @param examinationQuestionListVO
     * @return
     */
    @Override
    public IPage<QuestionBankSetExaminationQuestionListBO> getQuestionBankSetExaminationQuestionList(QuestionBankSetExaminationQuestionListVO questionBankSetExaminationQuestionListVO) {
        /* 校验 */
        if (StringUtils.isEmpty(questionBankSetExaminationQuestionListVO)) {
            logger.info("查询列表失败");
            throw new BaseException("-1", "传入数据有误");
        }
        String questionBankId = questionBankSetExaminationQuestionListVO.getQuestionBankId();
        Page<QuestionBankSetExaminationQuestionListBO> page =
            new Page<QuestionBankSetExaminationQuestionListBO>(questionBankSetExaminationQuestionListVO.getCurrentPage(), questionBankSetExaminationQuestionListVO.getPageSize());
        IPage<QuestionBankSetExaminationQuestionListBO> list = examinationQuestionMapper.getQuestionBankSetExaminationQuestionList(questionBankId, page);
        return list;
    }

    /**
     * 查询试题列表
     */
    @Override
    public IPage<ExaminationQuestionListBO> getExaminationQuestionList(ExaminationQuestionListVO examinationQuestionListVO) {
        /* 试题标题必须不为空 */
        if (checkListPageParam(examinationQuestionListVO)) {
            logger.info("查询列表失败");
            throw new BaseException("-1", "传入数据有误");
        }
        Page<ExaminationQuestionListBO> page = new Page<ExaminationQuestionListBO>(examinationQuestionListVO.getCurrentPage(), examinationQuestionListVO.getPageSize());
        return examinationQuestionMapper.getExaminationQuestionList(examinationQuestionListVO.getExaminationQuestionsTitle(), examinationQuestionListVO.getIsMultipleChoice(), page);
    }

    /**
     * 创建、修改试题信息
     */
    @Override
    @Transactional
    public String modifyExaminationQuestionInfo(ModifyExaminationQuestionInfoVO examinationQuestionInfoVO) {
        /* 判断传入数据是否合格 */
        if (examinationQuestionInfoVO == null) {
            logger.info("新增或修改失败");
            throw new BaseException("-1", "传入数据有误");
        }
        /* 校验必传参数 */
        if (StringUtils.isEmpty(examinationQuestionInfoVO.getExaminationQuestionsTitle()) || StringUtils.isEmpty(examinationQuestionInfoVO.getIsMultipleChoice())
            || examinationQuestionInfoVO.getExaminationQuestionsOptionVoList() == null || examinationQuestionInfoVO.getExaminationQuestionsOptionVoList().size() <= 0) {
            logger.info("新增或修改失败");
            throw new BaseException("-1", "有必填项未填！");
        }

        ExaminationQuestion examinationQuestion = new ExaminationQuestion();

        ExaminationQuestionsOption examinationQuestionsOption = new ExaminationQuestionsOption();

        /* 使用工具直接进行实体与BO的复制转换，注意字段名及类型需保持一致 */
        BeanUtil.copyProperties(examinationQuestionInfoVO, examinationQuestion);

        if (examinationQuestionInfoVO.getExaminationQuestionsId() == null || "".equals(examinationQuestionInfoVO.getExaminationQuestionsId())) {
            /* 新增试卷 */
            logger.info("新增试题基本信息");
            examinationQuestion.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            examinationQuestion.setCreateTime(new Date());
            examinationQuestion.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            examinationQuestion.setUpdateTime(new Date());
            examinationQuestion.setIsDelete(false);

            examinationQuestionMapper.insert(examinationQuestion);// 新建试题
            /*设置试题选项*/
            updateExaminationQuestionOptionInSetExaminationQuestion(examinationQuestion.getExaminationQuestionsId(), examinationQuestionInfoVO.getExaminationQuestionsOptionVoList());
        } else {
            /* 修改 */
            logger.info("修改试题基本信息");
            /* 设置修改人id */
            examinationQuestionsOption.setUpdateUserId(Objects.requireNonNull(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId()));
            examinationQuestionsOption.setUpdateTime(new Date());
            examinationQuestionMapper.updateById(examinationQuestion);
            // 修改某个试题选项为该试题正确试题选项
            examinationQuestionsOption.setIsCorrect(1);// 该试题选项为正确
            // 设置修改人id
            examinationQuestionsOption.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            // 设置修改时间
            examinationQuestionsOption.setUpdateTime(new Date());

            examinationQuestionMapper.updateById(examinationQuestion);// 修改试题选项

            // 设置试题选项
            updateExaminationQuestionOptionInSetExaminationQuestion(examinationQuestion.getExaminationQuestionsId(), examinationQuestionInfoVO.getExaminationQuestionsOptionVoList());
        }
        return examinationQuestion.getExaminationQuestionsId();
    }

    /**
     * 删除试题
     */
    @Override
    public Integer deleteExaminationQuestion(List<String> examinationQuestionIds) {
        /* 校验 */
        if (CollectionUtil.isEmpty(examinationQuestionIds)) {
            logger.info("删除失败");
            throw new BaseException("-1", "集合为空");
        }
        /* 批量逻辑删除产品 */
        return examinationQuestionMapper.deleteBatchIds(examinationQuestionIds);
    }

    /**
     * 获取该试题试题选项列表
     */
    @Override
    public List<ExaminationQuestionOptionListBO> getExaminationQuestionOptionList(ExaminationQuestionOptionListVO examinationQuestionOptionListVO) {
        List<ExaminationQuestionOptionListBO> examinationQuestionOptionListBO = new ArrayList<ExaminationQuestionOptionListBO>();

        if (checkListPageParam(examinationQuestionOptionListVO)) {
            logger.info("查询列表失败");
            throw new BaseException("-1", "传入数据有误");
        }
        /* 试题id */
        List<ExaminationQuestionsOption> examinationQuestionOptionList = null;
        QueryWrapper<ExaminationQuestionsOption> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(examinationQuestionOptionListVO.getExaminationQuestionsId())) { // 试题id为空
            return examinationQuestionOptionListBO;
        } else {
            queryWrapper.eq("EXAMINATION_QUESTIONS_ID", examinationQuestionOptionListVO.getExaminationQuestionsId());
            queryWrapper.orderByAsc("EXAMINATION_QUESTIONS_OPTION");
            examinationQuestionOptionList = examinationQuestionsOptionMapper.selectList(queryWrapper);
        }
        /* 以试题选项升序 */
        examinationQuestionOptionListBO = EntityToBeanUtils.copyBean(examinationQuestionOptionList, ExaminationQuestionOptionListBO.class);
        return examinationQuestionOptionListBO;
    }

    /**
     * 新建试题选项
     */
    @Override
    public String modifyExaminationQuestionOption(ModifyExaminationQuestionOptionVO modifyExaminationQuestionOptionVO) {
        if (modifyExaminationQuestionOptionVO == null) {
            throw new BaseException("-1", "传入数据有误");
        }
        ExaminationQuestionsOption examinationQuestionsOption = new ExaminationQuestionsOption();

        String examinationQuestionOptionId = modifyExaminationQuestionOptionVO.getExaminationQuestionsOptionId();
        /*如果有试题id就设置试题id*/
        if (!StringUtil.isNullOrEmpty(examinationQuestionOptionId)) {
            /*如果试题id不为空*/
            BeanUtil.copyProperties(modifyExaminationQuestionOptionVO, examinationQuestionsOption);
            /* 设置修改人id */
            examinationQuestionsOption.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            /* 设置修改时间 */
            examinationQuestionsOption.setUpdateTime(new Date());

            examinationQuestionsOptionMapper.updateById(examinationQuestionsOption);
        } else {
            BeanUtil.copyProperties(modifyExaminationQuestionOptionVO, examinationQuestionsOption);
            /* 新建试题选项 */
            examinationQuestionsOption.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            /* 设置创建时间 */
            examinationQuestionsOption.setCreateTime(new Date());
            /* 设置修改人id */
            examinationQuestionsOption.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            /* 设置修改时间 */
            examinationQuestionsOption.setUpdateTime(new Date());
            /* 设置删除标记 */
            examinationQuestionsOption.setIsDelete(false);

            examinationQuestionsOptionMapper.insert(examinationQuestionsOption);
        }
        logger.info("试题选项id" + examinationQuestionsOption.getExaminationQuestionsOptionId());
        return examinationQuestionsOption.getExaminationQuestionsOptionId();
    }

    /**
     * 删除试题选项
     */
    @Override
    public Integer deleteExaminationQuestionOptions(List<String> examinationQuestionsOptionIds) {
        /* 校验 */
        if (CollectionUtil.isEmpty(examinationQuestionsOptionIds)) {
            logger.info("删除失败");
            throw new BaseException("-1", "集合为空");
        }
        /* 批量逻辑删除产品 */
        return examinationQuestionsOptionMapper.deleteBatchIds(examinationQuestionsOptionIds);
    }

    /**
     * 校验分页参数
     * 
     * @param pageParam
     * @return
     */
    private boolean checkListPageParam(PageParam pageParam) {
        if (pageParam == null || pageParam.getPageSize() == null || pageParam.getCurrentPage() == null || StringUtils.isEmpty(pageParam.getPageSize())
            || StringUtils.isEmpty(pageParam.getCurrentPage()) || pageParam.getCurrentPage() < 1) {
            return true;
        }
        return false;
    }

    /**
     * 更新众多试题的题库id.
     */
    @Override
    public void updateExaminationQuestionSetQuestionBankId(String questionBankId, List<String> examinationQuestionIds) {
        if (questionBankId == null || examinationQuestionIds == null || examinationQuestionIds.size() <= 0) {
            throw new BaseException("-1", "传入数据有误");
        }

        ExaminationQuestion examinationQuestion = new ExaminationQuestion();

        examinationQuestion.setQuestionBankId(questionBankId);
        examinationQuestion.setUpdateTime(new Date());
        examinationQuestion.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));

        UpdateWrapper<ExaminationQuestion> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("EXAMINATION_QUESTIONS_ID", examinationQuestionIds);

        int affectRows = examinationQuestionMapper.update(examinationQuestion, updateWrapper);
        logger.info("修改了" + affectRows);
    }

    /* 
     * 试题设置(试题选项)
     */
    @Override
    @Transactional
    public void updateExaminationQuestionOptionInSetExaminationQuestion(String examinationQuestionId, List<ModifyExaminationQuestionOptionVO> modifyExaminationQuestionOptionVOList) {
        int correctNum = 0;

        /*删除指定试题的试题选项*/
        examinationQuestionsOptionMapper.deleteExaminationQuestionOptionsInExaminationQuestion(examinationQuestionId);
        /*新建试题选项*/
        for (ModifyExaminationQuestionOptionVO modifyExaminationQuestionOptionVO : modifyExaminationQuestionOptionVOList) {
            ExaminationQuestionsOption examinationQuestionOption = new ExaminationQuestionsOption();
            examinationQuestionOption.setExaminationQuestionsOption(modifyExaminationQuestionOptionVO.getExaminationQuestionsOption());
            examinationQuestionOption.setExaminationQuestionsOptionDescription(modifyExaminationQuestionOptionVO.getExaminationQuestionsOptionDescription());
            if (modifyExaminationQuestionOptionVO.getIsCorrect() == 1)
                correctNum++;
            examinationQuestionOption.setIsCorrect(modifyExaminationQuestionOptionVO.getIsCorrect());
            examinationQuestionOption.setExaminationQuestionsId(examinationQuestionId);
            examinationQuestionOption.setCreateTime(new Date());
            examinationQuestionOption.setIsDelete(false);
            examinationQuestionOption.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            examinationQuestionsOptionMapper.insert(examinationQuestionOption);
        }
        //试题选项中必须有一项正确
        if (correctNum == 0) {
            throw new BaseException("-1", "必须有正确试题选项");
        }
    }

    /**
     * 查询试卷设置试题列表.
     */
    @Override
    public IPage<ExaminationPaperSetExaminationQuestionListBO>
        getExaminationPaperSetExaminationQuestionList(ExaminationPaperSetExaminationQuestionListVO examinationPaperSetExaminationQuestionListVO) {
        if (StringUtils.isEmpty(examinationPaperSetExaminationQuestionListVO)) {
            logger.info("查询列表失败");
            throw new BaseException("-1", "传入数据有误");
        }
        // 获取题库id参数
        String examinationPaperId = examinationPaperSetExaminationQuestionListVO.getExaminationPaperId();
        Page<ExaminationPaperSetExaminationQuestionListBO> page =
            new Page<ExaminationPaperSetExaminationQuestionListBO>(examinationPaperSetExaminationQuestionListVO.getCurrentPage(), examinationPaperSetExaminationQuestionListVO.getPageSize());
        return examinationQuestionMapper.getExaminationPaperSetExaminationQuestionList(examinationPaperId, page);
    }

}
